
'''
药神保·抗癌特药保障计划（基础款）
'''

import sys
import warnings
warnings.filterwarnings('ignore')
sys.path.append('../..')
from common.config import *
from db.mysql import MysqlClient
from itertools import product
import requests
from urllib.parse import  urlencode
from common.helper import Helper


class Spider(object):
    def __init__(self):
        self.mysql = MysqlClient()
        self.name = "用药保抗癌特药医疗保险"

    # 生成产品数据
    def genProductInfo(self):
        plan = {

            "year": [str(i) for i in range(0, 66)],
            "socialSec": ["Y", "N"],
            "money": ["2000000"],
            "expire": ["1年"]
        }
        for v in product(plan["year"], plan["socialSec"], plan["money"], plan["expire"]):
            self.mysql.cursor.execute(domain[self.name]["insert_sql"].format(v[0], v[1], v[2], v[3]))
            self.mysql._conn.commit()
            print(domain[self.name]["insert_sql"].format(v[0], v[1], v[2], v[3]))

    # 执行爬虫
    def requestJson(self, dt=None):

        data = {"requestData":{"productId": "P123801", "isMulti": "1", "issueChannel": "1", "list": [
            {"cInsrncCde": "1", "nSelectFlag": "1", "nPrm": 0, "nAmt": "恶性肿瘤院外特定药品费用", "calculateFlag": "1",
             "insuredAmt": 0},
            {"cInsrncCde": "123801", "nSelectFlag": "1", "nPrm": 0, "nAmt": "200万元", "calculateFlag": "1",
             "insuredAmt": 2000000},
            {"cInsrncCde": "3", "nSelectFlag": "1", "nPrm": 0, "nAmt": "", "calculateFlag": "1", "insuredAmt": 0}],
                "nspFlag": "1", "premiumType": "2", "productPlanId": "P123801-T1",
                "insured_field|shebao|factor2Value|": "1" if dt["socialSec"] == "Y" else "0", "insured|age|factor1Value|": dt["year"], "securityPeriod": "1y"}
                }

        payload = urlencode(data)

        r = requests.post( url = domain[self.name]["url"],headers=domain[self.name]["header"],data=payload,verify=False)

        print( r.text )
        if r.status_code == 200 and r.json()["resultMsg"] == "交易成功" and r.json()["premium"] :

            price = Helper.decimalParse( r.json()["premium"])

            data = {

                "name":self.name,
                "id":dt["id"],
                "price":price
            }
            self.mysql.updatePrice( data )

        else:

            data = {

                "name": self.name,
                "id": dt["id"],
                "state": 3
            }
            self.mysql.updateTask(data)

    def main(self):

        while True:

            # 随机领取一条数据
            dt = self.mysql.randTask(self.name)

            if not dt:
                print("产品价格抓取完成~~~")

                return

                # 任务执行状态
            data = {
                "name": self.name,
                "id": dt["id"],
                "state": 1
            }
            self.mysql.updateTask(data)

            self.requestJson(dt)
